﻿Type.registerNamespace("jQueryNET.Utils");

function jQueryNET$Utils$JSON$serialize(v) {
	var a = [];
	//	Emit a string.
	function e(s) { a[a.length] = s; }

	// Convert a value.
	function g(x) {
		var b, c, i, l, v;
		var _ud = "undefined";
		
		switch (typeof x) {
			case 'string':
				e('"');
				if (/["\\\x00-\x1f\x7d\x5d]/.test(x)) {
					l = x.length;
					for (i = 0; i < l; i += 1) {
						c = x.charAt(i);
						if (c >= ' ' && c != '}' && c != ']') {
							if (c == '\\' || c == '"')
								e('\\');
							e(c);
						} else {
							switch (c) {
								case '\b':
									e('\\b');
									break;
								case '\f':
									e('\\f');
									break;
								case '\n':
									e('\\n');
									break;
								case '\r':
									e('\\r');
									break;
								case '\t':
									e('\\t');
									break;
								case '}':
									e('\\u007D');
									break;
								case ']':
									e('\\u005D');
									break;
								default:
									c = c.charCodeAt();
									e('\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16));
							}
						}
					}
				} else {
					e(x);
				}
				e('"');
				return;
			case 'number':
				e(isFinite(x) ? x : 'null');
				return;
			case 'object':
				if (x) {
					// RAS: Added Date Parsing
					if (x.toUTCString)
						return e('\"\\/Date(' + x.getTime() + ')\\/\"'); // MS Ajax style

					if (x instanceof Array) {
						e('[');
						l = a.length;
						for (i = 0; i < x.length; i += 1) {
							v = x[i];
							if (typeof v != _ud && typeof v != 'function') {
								if (b) { e(','); }
								g(v);
								b = true;
							}
						}
						e(']');
						return;
					} else if (typeof x.valueOf == 'function') {
						e('{');
						l = a.length;
						for (i in x) {
							v = x[i];
							if (typeof v != _ud && typeof v != 'function' && (!v || typeof v != 'object' || typeof v.valueOf == 'function')) {
								if (b) { e(','); }
								g(i);
								e(':');
								g(v);
								b = true;
							}
						}
						return e('}');
					}
				}
				e('null');
				return;
			case 'boolean':
				e(x);
				return;
			default:
				e('null');
				return;
		}
	}
	g(v);
	return a.join('');
}

function jQueryNET$Utils$JSON$_regExDate(str, p1, p2, offset, s) {
	str = str.substring(1).replace('"', '');
	var date = str;
	//MS Ajax date
	var regEx = /\/Date(.*)\//;
	if (regEx.test(str)) {
		str = str.match(/Date\((.*?)\)/)[1];
		date = "new Date(" + parseInt(str) + ")";
	}
	else { // ISO Date 2007-12-31T23:59:59Z
		var matches = str.split(/[-,:,T,Z]/);
		matches[1] = (parseInt(matches[1], 0) - 1).toString();
		date = "new Date(Date.UTC(" + matches.join(",") + "))";
	}
	return date;
}

function jQueryNET$Utils$JSON$_parse(text, noCheck) {
	if (!noCheck && !(!(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(text.replace(/"(\\.|[^"\\])*"/g, '')))))
		throw new Error("Invalid characters in JSON parse string.");

	// *** RAS Update:  Fix up Dates: ISO and MS AJAX format support
	var regEx = /(\"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}.*?\")|(\"\\*\/Date\(.*?\)\\*\/")/g;
	//var regEx = /(\"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}.*?\")|(\"\\\/Date\(.*?\)\\\/")/g;
	text = text.replace(regEx, this._regExDate);

	return eval('(' + text + ')');
}

function jQueryNET$Utils$JSON$parse(text) {
	try {
		return this._parse(text);
	}
	catch (e) {
		return null;
	}
}

jQueryNET.Utils.JSON = {
	_regExDate: jQueryNET$Utils$JSON$_regExDate,
	_parse: jQueryNET$Utils$JSON$_parse,
	parse: jQueryNET$Utils$JSON$parse,
	serialize: jQueryNET$Utils$JSON$serialize
}

jQueryNET.Utils.WebService = function jQueryNET$Utils$WebService(url) {
	var e = Function._validateParams(arguments, [
		{ name: "url", type: String, mayBeNull: false }
	]);
	if (e) throw e;
	this._url = url;
}

function jQueryNET$Utils$WebService$get_sendMethod() {
	if (arguments.length !== 0) throw Error.parameterCount();
	return this._sendMethod;
}

function jQueryNET$Utils$WebService$set_sendMethod(value) {
	var e = Function._validateParams(arguments, [
		{ name: "value", type: String, mayBeNull: false }
	]);
	if (e) throw e;
	this._sendMethod = value;
}

function jQueryNET$Utils$WebService$get_contentType() {
	if (arguments.length !== 0) throw Error.parameterCount();
	return this._contentType;
}

function jQueryNET$Utils$WebService$set_contentType(value) {
	var e = Function._validateParams(arguments, [
		{ name: "value", type: String, mayBeNull: false }
	]);
	if (e) throw e;
	this._contentType = value;
}

function jQueryNET$Utils$WebService$get_timeout() {
	if (arguments.length !== 0) throw Error.parameterCount();
	return this._timeout;
}

function jQueryNET$Utils$WebService$set_timeout() {
	var e = Function._validateParams(arguments, [
		{ name: "value", type: Number, mayBeNull: false }
	]);
	if (e) throw e;
	this._timeout = value;
}

function jQueryNET$Utils$WebService$invoke(method, params, completedCallback, errorCallback) {
	var e = Function._validateParams(arguments, [
		{ name: "method", type: String, mayBeNull: false },
		{ name: "params", type: Object, mayBeNull: true, optional: true },
		{ name: "completedHandler", type: Function, mayBeNull: true, optional: true },
		{ name: "errorHandler", type: Function, mayBeNull: true, optional: true }
	]);
	if (e) throw e;

	var fullUrl = String.format("{0}/{1}", this._url, method);
	var json_params = jQueryNET.Utils.JSON.serialize(params);

	$.ajax({
		url: fullUrl,
		data: json_params,
		type: (json_params ? "POST" : this.get_sendMethod()),
		processData: false,  // always process on our own!
		contentType: this.get_contentType(),
		timeout: this.get_timeout(),
		dataType: "text",
		global: false,
		//async: _I.async,
		//beforeSend: function(xhr) {
		//	for (var header in _I.headers)
		//		xhr.setRequestHeader(header, _I.headers[header]);
		//},
		success: function(result, status) {
			var errorException = null;

			try {
				result = jQueryNET.Utils.JSON.parse(result);
				if (result != null) {
					if (result.d)
						result = result.d;
//					else if (_I.isMsAjaxJson) {
//						// Wrapped message: return first property
//							for (var property in result) {
//								result = result[property];
//								break;
//							}
//						}
				}
			}
			catch (e) {
				errorException = e;
			}
			
			if (errorException) {
				if (errorCallback)
					errorCallback(errorException, null, this);
				return;
			}

			if (result && (result.isCallbackError || result.iscallbackerror)) {
				if (errorCallback)
					errorCallback(result, null, this);
			}
			
			if (completedCallback)
				completedCallback(result, this);
		},
			
		error: function(xhr, status) {
			var res = xhr.responseText;
			var message = null;
			var detail = null;
			if (res && res.charAt(0) == '{')
				var message = jQueryNET.Utils.JSON.parse(res);
			if (!message) {
				if (xhr.status != 200)
					message = xhr.status + " " + xhr.statusText;
				else
					message = "Unknown Error Response";
				detail = res;
			}

			if (errorCallback)
				errorCallback(message, detail, this);
		}
	});
}

jQueryNET.Utils.WebService.prototype = {
	_url: null,
	_params: null,
	_sendMethod: "GET",
	_contentType: "application/json",
	_timeout: 20000,

	get_sendMethod: jQueryNET$Utils$WebService$get_sendMethod,
	set_sendMethod: jQueryNET$Utils$WebService$set_sendMethod,
	get_contentType: jQueryNET$Utils$WebService$get_contentType,
	set_contentType: jQueryNET$Utils$WebService$set_contentType,
	get_timeout: jQueryNET$Utils$WebService$get_timeout,
	set_timeout: jQueryNET$Utils$WebService$set_timeout,
	invoke: jQueryNET$Utils$WebService$invoke
}

jQueryNET.Utils.WebService.registerClass("jQueryNET.Utils.WebService");

function jQueryNET$Utils$WebService$contains(owner, element) {
	if (owner == element)
		return true;
		
	var parent = $(element).parent()
	var body = $('body');
	
	while (	parent.size() > 0 &&
			parent.get(0) != owner &&
			parent != body)
	{
		parent = parent.parent()
	}

	return (parent.size() > 0 &&
			parent.get(0) == owner)
}

jQueryNET.Utils.Dom = {
	contains: jQueryNET$Utils$WebService$contains
}
